package processes

import (
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/client/model"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/constants"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/message"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/netWork"
)

var (
	userManagerProcess *UserManagerProcess
	curUser            *model.CurUser
)

type UserManagerProcess struct {
	Friends map[int]message.User
}

func (userMgr *UserManagerProcess) InitFriends(friends []message.User) {
	for _, friend := range friends {
		userMgr.Friends[friend.UserId] = friend
	}
}

func (userMgr *UserManagerProcess) AddFriends(userId int, userName string) {
	userMgr.Friends[userId] = message.User{
		UserId:     userId,
		UserName:   userName,
		UserStatus: constants.USER_STATUS_OFFLINE,
	}
}

func (userMgr *UserManagerProcess) UpdateOnlineUser(userId, status int) {
	user, ok := userMgr.Friends[userId]
	if !ok {
		return
	}
	user.UserStatus = status
	userMgr.Friends[userId] = user
}

func (userMgr *UserManagerProcess) GetOnlineFriends() (onlineFriends []message.User) {
	onlineFriends = make([]message.User, 0)
	for _, user := range userMgr.Friends {
		if user.UserStatus != constants.USER_STATUS_OFFLINE {
			onlineFriends = append(onlineFriends, user)
		}
	}
	return
}

func (userMgr *UserManagerProcess) OutputOnlineFriends() {
	onlineFriends := userMgr.GetOnlineFriends()
	fmt.Printf("当前在线用户(%d人)：\n", len(onlineFriends))
	for _, user := range onlineFriends {
		fmt.Printf("%s(ID:%d)\n", user.UserName, user.UserId)
	}
}

func init() {
	userManagerProcess = &UserManagerProcess{
		Friends: make(map[int]message.User),
	}
}

func initCurUser(conn netWork.Conn, user message.User) {
	curUser = &model.CurUser{Conn: conn}
	curUser.UserId = user.UserId
	curUser.UserName = user.UserName
	curUser.UserStatus = user.UserStatus
}
